﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Unity聊天室_socket_服务器端
{
    class Client
    {
        private Socket tcpClient; 
        private Thread t;
        private byte[] data = new byte[1024];//这是一个数据容器
        public Client(Socket s)
        {
            tcpClient = s;
            //启动线程去处理客户端数据的接收
             t = new Thread(ReceiveMessage);
            t.Start();
        }
        private void ReceiveMessage()
        {
            //一直接收客户端的数据
            while (true)
            {
                //在接受数据之前先判断下socket连接是否断开
                if (tcpClient.Poll(10, SelectMode.SelectRead) == true)
                {
                    tcpClient.Close();
                    break; //跳出循环，终止线程
                }
                int length =  tcpClient.Receive(data);
                string message = Encoding.UTF8.GetString(data, 0, length);
                
                Program.BroadcastMessage(message);
                if (message != "")
                    Console.WriteLine("Message Received: " + message);
                else
                    Console.WriteLine("Disconnected!!");  
            }
        }
        public void SendMessages(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            tcpClient.Send(data);
        }
        public bool Connected
        {
            get { return tcpClient.Connected; }
        }


    }
}
